<template>
  <view class="profile-container">
    <!-- 导航栏 -->
    <u-navbar :title="useT('个人资料')" left-icon="arrow-left" leftIconSize="50rpx" bg-color="transparent" :border="false" title-style="color: #000;font-weight: bold;" placeholder @leftClick="goBack"></u-navbar>

    <!-- 头像区域 -->
    <view class="avatar-section">
      <view class="avatar-container" @click="chooseAvatar">
        <image class="avatar" :src="formData.avatar || '/static/default-avatar.png'" mode="aspectFill" />
        <view class="avatar-overlay">
          <u-icon name="camera" size="40rpx" color="#ffffff"></u-icon>
        </view>
      </view>
      <text class="avatar-tip">{{ useT('点击更换头像') }}</text>
    </view>

    <!-- 表单区域 -->
    <view class="form-section">
      <view class="form-item">
        <text class="form-label">{{ useT('昵称') }}</text>
        <u-input v-model="formData.nickname" :placeholder="useT('请输入昵称')" border="none" class="form-input" />
      </view>
    </view>

    <!-- 保存按钮 -->
    <view class="save-button-container">
      <u-button
        :loading="loading"
        :disabled="!canSave"
        @click="saveProfile"
        class="save-button"
        type="primary"
        :custom-style="{
          backgroundColor: '#12C284',
          borderColor: '#12C284',
          borderRadius: '12rpx',
          height: '88rpx',
          fontSize: '32rpx',
          fontWeight: 'bold'
        }"
      >
        {{ useT('保存') }}
      </u-button>
    </view>
  </view>
</template>

<script setup>
import { uploadImage } from '@/api/common.js';
import { editUserInfo, getUserInfo } from '@/api/user.js';
import { useUserStore } from '@/stores/user.js';
import { useT } from '@/utils/i18n.js';
import { computed, onMounted, ref } from 'vue';

const userStore = useUserStore();

// 表单数据
const formData = ref({
  avatar: '',
  nickname: '',
  country_region: ''
});

// 加载状态
const loading = ref(false);

// 计算是否可以保存
const canSave = computed(() => {
  return formData.value.nickname.trim().length > 0;
});

// 页面加载时获取用户信息
onMounted(() => {
  loadUserInfo();
});

// 加载用户信息
const loadUserInfo = async () => {
  try {
    const res = await getUserInfo();
    if (res.status === 200) {
      formData.value = {
        avatar: res.data.avatar || '',
        nickname: res.data.nickname || ''
      };
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
    uni.showToast({
      title: useT('获取用户信息失败'),
      icon: 'none'
    });
  }
};

// 选择头像
const chooseAvatar = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: async (res) => {
      try {
        // 显示上传进度
        uni.showLoading({
          title: useT('上传中.')
        });

        // 获取选择的图片路径
        const tempFilePath = res.tempFilePaths[0];

        // 生成文件名
        const timestamp = Date.now();
        const filename = `avatar_${timestamp}.jpg`;
        // 调用上传接口
        const uploadRes = await uploadImage({
          filename,
          filePath: tempFilePath
        });

        if (uploadRes.status === 200) {
          // 上传成功，更新头像
          formData.value.avatar = uploadRes.data.url;
          uni.hideLoading();
          uni.showToast({
            title: useT('上传成功'),
            icon: 'success'
          });
        } else {
          throw new Error(uploadRes.msg || useT('上传失败'));
        }
      } catch (error) {
        console.error('上传头像失败:', error);
        uni.hideLoading();
        uni.showToast({
          title: error.message || useT('上传失败'),
          icon: 'none'
        });
      }
    },
    fail: (error) => {
      console.error('选择头像失败:', error);
      uni.showToast({
        title: useT('选择图片失败'),
        icon: 'none'
      });
    }
  });
};

// 保存个人资料
const saveProfile = async () => {
  if (!canSave.value) {
    uni.showToast({
      title: useT('请填写完整信息'),
      icon: 'none'
    });
    return;
  }

  loading.value = true;

  try {
    const res = await editUserInfo({
      avatar: formData.value.avatar,
      nickname: formData.value.nickname
    });

    if (res.status === 200) {
      // 更新本地用户信息
      const userRes = await getUserInfo();
      if (userRes.status === 200) {
        userStore.setUserInfo(userRes.data);
      }

      uni.showToast({
        title: useT('保存成功'),
        icon: 'success'
      });

      // 延迟返回上一页
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    } else {
      uni.showToast({
        title: res.msg || useT('保存失败'),
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('保存个人资料失败:', error);
    uni.showToast({
      title: useT('保存失败，请重试'),
      icon: 'none'
    });
  } finally {
    loading.value = false;
  }
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};
</script>

<style lang="scss" scoped>
.profile-container {
  min-height: 100vh;
  background: linear-gradient(to bottom, #e3f8fe 10%, #f8f8f8 50%);
  padding-bottom: 40rpx;

  // 头像区域
  .avatar-section {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 60rpx 0 40rpx;

    .avatar-container {
      position: relative;
      margin-bottom: 20rpx;

      .avatar {
        width: 160rpx;
        height: 160rpx;
        border-radius: 80rpx;
        background: #f0f0f0;
        border: 4rpx solid #ffffff;
        box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
      }

      .avatar-overlay {
        position: absolute;
        bottom: 0;
        right: 0;
        width: 48rpx;
        height: 48rpx;
        background: #12c284;
        border-radius: 24rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        border: 4rpx solid #ffffff;
      }
    }

    .avatar-tip {
      font-size: 28rpx;
      color: #666666;
    }
  }

  // 表单区域
  .form-section {
    background: #ffffff;
    border-radius: 16rpx;
    margin: 0 30rpx 40rpx;
    padding: 0 30rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);

    .form-item {
      display: flex;
      align-items: center;
      padding: 40rpx 0;
      border-bottom: 1rpx solid #f5f5f5;

      &:last-child {
        border-bottom: none;
      }

      .form-label {
        font-size: 32rpx;
        color: #333333;
        font-weight: bold;
        width: 120rpx;
        margin-right: 20rpx;
      }

      .form-input {
        flex: 1;
        font-size: 32rpx;
        color: #333333;
      }
    }
  }

  // 保存按钮
  .save-button-container {
    padding: 0 30rpx;

    .save-button {
      width: 100%;
    }
  }
}
</style>
